<!--
table demo
@zhujing-->
<template>
  <div class="page-table-demo">
    <!--搜索条件-->
    <p-switch-form :col="3" :model="query">
      <p-switch-form-item label="姓名">
        <p-input
          v-model="query.name"
          allow-clear
          @pressEnter="search"
          @change="search"
        />
      </p-switch-form-item>
      <p-switch-form-item label="性别">
        <p-select v-model="query.sex">
          <p-select-option value="">全部</p-select-option>
          <p-select-option value="保密">保密</p-select-option>
          <p-select-option value="男">男</p-select-option>
          <p-select-option value="女">女</p-select-option>
        </p-select>
      </p-switch-form-item>
      <p-switch-form-item label="出生日期">
        <p-date-picker v-model="query.birth" />
      </p-switch-form-item>
      <p-switch-form-item label="年龄">
        <p-select v-model="query.age">
          <p-select-option value="">全部</p-select-option>
        </p-select>
      </p-switch-form-item>
      <template slot="button">
        <p-button icon="search" type="primary" @click="search">搜索</p-button>
        <p-button @click="reset">清空</p-button>
      </template>
    </p-switch-form>
    <div class="text-right pb-2">
      <p-button-group class="mr-2">
        <p-button icon="plus" type="primary" @click="add">新增</p-button>
      </p-button-group>
      <p-button-group>
        <p-button @click="importFile">导入</p-button>
        <p-button @click="exportFile">导出</p-button>
        <p-popover
          class="col-config"
          placement="bottom"
          trigger="click"
          :visible="isColCfgVisible"
          @visibleChange="colCfgVisibleChange"
        >
          <p-button>
            列显示
            <p-icon
              :type="!isColCfgVisible ? 'down' : 'up'"
              class="caption ml-1"
            />
          </p-button>
          <div slot="content" class="col-config-list">
            <div
              v-for="col in columns"
              :key="col.key"
              :class="{
                'col-config-item': true,
                'col-config-item--active': colCfgCache[col.key],
              }"
              @click="updateColCfgCache(col.key)"
            >
              <div>{{ col.title }}</div>
              <p-icon type="check" />
            </div>
          </div>
        </p-popover>
      </p-button-group>
    </div>
    <!--表格-->
    <p-table
      row-key="id"
      :loading="loading"
      :columns="visibleCols"
      :data-source="tableData"
      bordered
      :pagination="pagination"
      @change="tablePageChange"
    >
      <template slot="operation" slot-scope="text, record">
        <p-button-link @click="edit(record)">编辑</p-button-link>
        <p-divider type="vertical" />
        <p-button-link type="danger" @click="del(record)">删除</p-button-link>
      </template>
    </p-table>
    <!--弹框-->
    <p-modal
      v-model="isModalVisible"
      :title="modalTitle"
      v-bind="modalBtns"
      destroy-on-close
    >
      <p-form-model
        ref="modalForm"
        v-bind="modalFormLayout"
        :model="modalForm"
        :rules="modalRules"
      >
        <p-form-model-item label="姓名" prop="name">
          <p-input v-model="modalForm.name" placeholder="请输入姓名" />
        </p-form-model-item>
        <p-form-model-item label="性别" prop="sex">
          <p-select v-model="modalForm.sex">
            <p-select-option value="保密">保密</p-select-option>
            <p-select-option value="男">男</p-select-option>
            <p-select-option value="女">女</p-select-option>
          </p-select>
        </p-form-model-item>
        <p-form-model-item label="出生日期" prop="birth">
          <p-date-picker v-model="modalForm.birth" />
        </p-form-model-item>
        <p-form-model-item label="年龄">
          <p-input :value="age" read-only placeholder="根据出生日期自动计算" />
        </p-form-model-item>
        <p-form-model-item label="邮箱" prop="email">
          <p-input v-model="modalForm.email" placeholder="请输入邮箱地址" />
        </p-form-model-item>
        <p-form-model-item label="备注" prop="remark">
          <p-textarea v-model="modalForm.remark" placeholder="备注说明" />
        </p-form-model-item>
      </p-form-model>
    </p-modal>
  </div>
</template>

<script>
import moment from 'moment';
import {
  getItem,
  postItem,
  editItem,
  deleteItem,
  exportItem,
} from '@/api/demoTable';
import { createForm } from 'poros/utils';
//  form类方便init和reset等
const Form = createForm({
  name: '',
  sex: '保密',
  age: '',
  birth: '',
  email: '',
  remark: '',
});
const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    key: 'id',
    isShow: true,
  },
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    isShow: true,
  },
  {
    title: '性别',
    dataIndex: 'sex',
    key: 'sex',
    isShow: true,
  },
  {
    title: '出生日期',
    dataIndex: 'birth',
    key: 'birth',
    isShow: true,
  },
  {
    title: '年龄',
    dataIndex: 'age',
    key: 'age',
    isShow: true,
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    isShow: true,
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
    isShow: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: 120,
    selected: true,
    fixed: 'right',
    scopedSlots: { customRender: 'operation' },
    isShow: true,
  },
];

export default {
  name: 'PageDemoTable',
  data() {
    return {
      collapsed: false,
      loading: false,
      submitting: false,
      query: new Form({
        keyword: '',
        limit: 10,
        name: '',
        pageNo: 1,
      }),
      isModalVisible: false,
      modalForm: new Form(),
      modalRules: {
        name: [{ required: true, message: '请输入姓名' }],
        sex: [{ required: true, message: '请选择性别' }],
        birth: [{ required: true, message: '请选择出生日期' }],
      },
      modalFormLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 },
      },
      modalBtns: {
        okButtonProps: {
          on: {
            click: this.modalOk,
          },
          props: {
            icon: 'plus-circle',
            loading: this.submitting,
          },
        },
        cancelButtonProps: {
          on: {
            click: this.modalCancel,
          },
        },
      },
      columns,
      colCfgCache: {},
      isColCfgVisible: false,
      tableData: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '30', '50'],
        showTotal: (total) => `共有 ${total} 条数据`,
      },
    };
  },
  computed: {
    visibleCols() {
      return this.columns.filter((v) => v.fixed || v.isShow);
    },
    modalTitle() {
      return this.modalForm.id ? '编辑' : '新增';
    },
    age() {
      if (this.modalForm.birth) {
        return moment().year() - this.modalForm.birth.year();
      } else {
        return '';
      }
    },
  },
  mounted() {
    this.getTableData();
  },
  methods: {
    // 搜索
    search() {
      if (!this.loading) this.getTableData(1);
    },
    reset() {
      this.query.reset();
    },
    colCfgVisibleChange(visible) {
      this.isColCfgVisible = visible;
      if (this.isColCfgVisible) {
        this.colCfgCache = this.columns.reduce(function (
          cache,
          { key, fixed, isShow }
        ) {
          if (!fixed) cache[key] = isShow;
          return cache;
        },
        {});
      }
    },
    updateColCfgCache(key) {
      this.colCfgCache[key] = !this.colCfgCache[key];
    },
    updateColCfg() {
      this.isColCfgVisible = false;
      this.columns.forEach((col) => {
        col.isShow = this.colCfgCache[col.key];
      });
    },
    // 获取表格数据
    getTableData(pageNo) {
      if (this.loading) return;
      this.loading = true;
      if (Number.isInteger(pageNo)) {
        this.pagination.current = this.query.pageNo = pageNo;
      }
      getItem(this.query)
        .then((res) => {
          if (res.data && res.data.code === 0) {
            this.tableData = res.data.data.records;
            this.pagination.total = res.data.data.total;
          } else {
            this.$message.error({
              content: res.data.msg,
            });
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    tablePageChange({ current, pageSize }) {
      this.pagination.current = current;
      this.pagination.pageSize = pageSize;
      this.getTableData(current);
    },
    add() {
      this.modalForm.init();
      this.isModalVisible = true;
    },
    edit(row) {
      this.modalForm = new Form({
        ...row,
        birth: row.birth ? moment(row.birth) : '',
      });
      this.isModalVisible = true;
    },
    //excel导出
    exportFile() {
      exportItem(this.query);
    },
    //excel导入
    importFile() {
      alert('test');
    },
    // 新增或者编辑提交
    modalOk() {
      if (this.submitting) return;
      this.$refs.modalForm.validate((valid) => {
        if (!valid) return false;
        const data = {
          name: this.modalForm.name,
          sex: this.modalForm.sex,
          age: this.age,
          birth: this.modalForm.birth.format('yyyy-MM-DD'),
          email: this.modalForm.email,
          remark: this.modalForm.remark,
        };
        let api = postItem;
        if (this.modalForm.id) {
          data.id = this.modalForm.id;
          api = editItem;
        }
        this.submitting = true;
        api(data)
          .then((res) => {
            if (res.data && res.data.code === 0) {
              this.$message.success({ content: this.modalTitle + '成功！' });
              this.isModalVisible = false;
              this.getTableData(1);
            } else {
              this.$message.error({ content: res.data.msg });
            }
          })
          .finally(() => {
            this.submitting = false;
          });
      });
    },
    modalCancel() {
      this.isModalVisible = false;
    },
    del(row) {
      this.$confirm({
        content: '是否确认删除？',
        onOk: () => {
          deleteItem(row.id).then((res) => {
            if (res.data && res.data.code === 0) {
              this.$message.success({ content: '删除成功！' });
              this.getTableData();
            } else {
              this.$message.error({ content: res.msg });
            }
          });
        },
        onCancel: () => {},
      });
    },
  },
};
</script>

<style lang="less">
.page-table-demo {
  .poros-btn-group {
    margin-top: 0 !important;
  }
}

.col-config-list {
  margin: -7px -16px;
}

.col-config-item {
  padding: 8px 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  &:hover {
    background: #eaeaeb;
    color: @primary-color;
    cursor: pointer;
  }

  :nth-child(2) {
    opacity: 0;
    margin-left: 10px;
  }

  &--active :nth-child(2) {
    opacity: 1;
  }
}
</style>
